package com.woniuxy.handler;


import com.woniuxy.config.WebSocketUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@RestController
@ServerEndpoint("/WebSocketHandler/{userName}")
public class WebSocketHandler {
    @OnOpen
    public void openSession(@PathParam("userName") String userName, Session session){
        String message = "欢迎:"+userName +"加入群聊";
        WebSocketUtil.messageMap.put(userName,session);
        //给所有人发消息
        WebSocketUtil.sendAll(message);

    }
    @OnMessage
    public void onMessage(@PathParam("userName") String userName, String message){
        message = userName +":" +message;
        WebSocketUtil.sendAll(message);
    }


    @OnClose
    public void onClose(@PathParam("userName") String userName,Session session){
        WebSocketUtil.messageMap.remove(userName);
        WebSocketUtil.sendAll("用户:"+userName+"离开聊天室");

        try {
            session.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
